import socket
import struct
import textwrap

TAB_1 = "\t - "
TAB_2 = "\t\t - "
TAB_3 = "\t\t\t - "
TAB_4 = "\t\t\t\t - "

DATA_TAB_1 = "\t "
DATA_TAB_2 = "\t\t "
DATA_TAB_3 = "\t\t\t "
DATA_TAB_4 = "\t\t\t\t\t "

class Sniffer:
    def __init__(self, conn):
        self.conn = conn
    def Catch(self):
        raw_data, addr = self.conn.recvfrom(65536)
        dest_mac, src_mac, eth_proto, data = self.ethernet_frame(raw_data)
        # type = getpackettype(self, eth_proto)

        return ('目的地址:{}, 源地址: {}, 协议：{}\n').format(dest_mac, src_mac, eth_proto)
    def ethernet_frame(self,data):
        dest_mac, src_mac, proto = struct.unpack('! 6s 6s H', data[:14])
        return self.get_mac_addr(dest_mac), self.get_mac_addr(src_mac), socket.htons(proto), data[14:]
    def get_mac_addr(self,bytes_addr):
        bytes_str = map('{:02x}'.format ,bytes_addr)
        return ':'.join(bytes_str).upper()
    # def getpackettype(self, eth_proto):

conn = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(3))
a = Sniffer(conn)
# while True:
#     a.Catch()